<?php
namespace Wx\Controller;
use Think\Controller;
use Think\Model;

class AddressController extends BaseController
{
    public $userid;
    public function _initialize()
    {
        parent::isLogin();
        @header('Content-type: text/html;charset=UTF-8');
        if (session('oto_userId')) {
            $this->userid = session('oto_userId');
        }
    }


    // 获取省
    public function getCity($parentid=0) {
        $m = M ( 'areas' );
        $I_parentId=I( 'parentId' );
        if(isset($parentid)&&empty($I_parentId)){
            $pid=$parentid;
        }else{
            $pid = I ( 'parentId' ) ? I ( 'parentId' ) : 0;
        }
        $map ['areaFlag'] = 1;
        //$map['isShow']=1;
        $field = "areaId,areaName";
        $map ['parentId'] = $pid;
        $res = $m->where ( $map )->field ( $field )->select ();

        if(IS_AJAX){
            $this->ajaxReturn($res);
        }else{
            return $res;
        }
    }




    public function getCommunitys($area1,$area2,$area3){
        $res = M('communitys')->field('communityId,communityName')->where(array('areaId1'=>$area1,'areaId2'=>$area2,'areaId3'=>$area3))->select();
        if(IS_AJAX){
            $this->ajaxReturn($res);
        }
    }

    //添加
    public function Add(){
        $map['userId']=session('oto_userId');
        $map['userName']=I('userName');
        $map['userPhone']=I('userPhone');
        $map['lng']=I('lng');
        $map['lat']=I('lat');
        $map['number']=I('number');
        $map['address']=I('address');
        $map['communityId']=I('CommunityId',0);
        $map['createTime']=date('Y-m-d H:i:s',time());
        $r=M('user_address')->add($map);
        if($r){
            $this->ajaxReturn(array('status'=>0));
        }else{
            $this->ajaxReturn(array('status'=>-1));
        }
    }

    //查询 地址
    public function getUserAddr(){
        $field="addressId,userName,userPhone,address,areaId1,areaId2,areaId3,isDefault,communityId";
        $map['addressFlag']=1;
        $map['isDefault']=1;
        $map['userId']=session('oto_userId');
        $addrInfo=M('user_address')->field($field)->order('isDefault DESC')->where($map)->limit(1)->select();
        $db=M('areas');
        foreach($addrInfo as $k=>$v){
            $addrInfo[$k]['province']=$db->where(array('areaId'=>$v['areaId1']))->getField('areaName');
            $addrInfo[$k]['city']=$db->where(array('areaId'=>$v['areaId2']))->getField('areaName');
            $addrInfo[$k]['area']=$db->where(array('areaId'=>$v['areaId3']))->getField('areaName');
            $addrInfo[$k]['community']=M('communitys')->where(array('communityId'=>$v['communityId']))->getField('communityName');
        }
        $this->ajaxReturn($addrInfo);
    }

    //收货地址
    public function myAddr(){
        $addr=M('user_address')->where(array('addressFlag'=>1,'userId'=>session('oto_userId')))->select();

        $ares=M('areas')->select();
        foreach ($addr as $k=>$v){
            $addr[$k]['isCan'] = 1;
            foreach ($ares as $a=>$av){
                if($v['areaId1']==$av['areaId']){
                    $addr[$k]['province']=$av['areaName'];
                }
                if($v['areaId2']==$av['areaId']){
                    $addr[$k]['city']=$av['areaName'];
                }
                if($v['areaId3']==$av['areaId']){
                    $addr[$k]['area']=$av['areaName'];
                }
            }
        }
        //标记确认订单跳转
        $this->isRef = 0;
        if (I('ref')) {
            $this->isRef = 1;
            //如果是订单确认，分拣是否在商店距离内的地址
            $url = explode('/',I('ref'));
            $shopInfo = M('shops')->where(['shopId' => $url['5']])->find();
            $ptm = D("Wx/Search")->getPtDeliveryConfig();
            //计算平台配送距离
            if ($shopInfo['deliveryType'] == 1 && !empty($ptm)) {
                $lat2 = $shopInfo['latitude'];
                $lon2 = $shopInfo['longitude'];
                foreach ($addr as $k => $v) {
                    $lat = $v['lat'];
                    $lon = $v['lng'];
                    $shopInfo['juli'] = D("Wx/Search")->getDistance($lat, $lon, $lat2, $lon2);
                    if ($shopInfo['juli']) {
                        for ($j = 0; $j < count($ptm); $j++) {
                            if($shopInfo['juli'] > $ptm[$j]['go_distance'] * 1000 && $j == count($ptm) - 1){
                                //距离外
                                $addr[$k]['isCan'] = 0;
                            }
                        }
                    }
                }
            }
        }
        $this->ref = I('ref')?I('ref'):'/Wx/Index/index/r/my';
        $this->addr=$addr;
        $this->display('myAddr');
    }

    //设置为默认地址
    public function setDefaultAddr(){
        if(!session('oto_userId')){
            $this->ajaxReturn(array('status'=>-3));
            return;
        }
        $id=I('addrid');
        M()->startTrans();
        $A=M('user_address')->where(array('userId'=>session('oto_userId')))->setField(array('isDefault'=>0));
        $B=M('user_address')->where(array('userId'=>session('oto_userId'),'addressId'=>$id))->setField(array('isDefault'=>1));
        if($A!==false&&$B!==false){
            M()->commit();
            $this->ajaxReturn(array('status'=>-0));
        }else{
            $this->ajaxReturn(array('status'=>-1));
            M()->rollback();
        }
    }

    //删除地址
    public function delAddr(){
        if(!session('oto_userId')){
            $this->ajaxReturn(array('status'=>-3));
            return;
        }
        $id=I('addrid');
        $A=M('user_address')->where(array('userId'=>session('oto_userId'),'addressId'=>$id))->delete();
        if($A){
            $this->ajaxReturn(array('status'=>-0));
        }else{
            $this->ajaxReturn(array('status'=>-1));
        }
    }

    public function addAddress(){
        $info=$this->getCity(0);
        $this->assign('areaInfo',$info);

        $this->display();
    }

    //添加地址
    public function addAddr(){
        parent::isLogin();
        $this->area=$this->getArea();

        if(I('ref')){
            //点击返回按钮url
            $this->ref = '/Wx/Address/myAddr?ref='.I('ref');
        }else{
            $this->ref = '/Wx/Address/myAddr';
        }

        $this->ret = $_SERVER['REQUEST_URI'];
        $this->display('edit_address');
    }

    public function getArea(){
        $m = M('areas');
        $conf= ['areaFlag'=>1];
        $area = $m-> where($conf) ->select();
        return $this->data_to_tree($area);
    }

    //整理地址为树形结构
    public function data_to_tree($temp, $topid = 0){
            $items=[];
            foreach($temp as $k=>$v){
                $items[$v['areaId']] = $v;
            }

            foreach ($items as $item)
                    $items[ $item['parentId'] ]['children'][] = &$items[ $item['areaId'] ];
            return isset($items[ $topid ]['children']) ? $items[ $topid ][ 'children' ] : [];

    }
    //添加地址处理
    public function addAddrHandle(){
        if(!session('oto_userId')){
            $this->ajaxReturn(array('status'=>-3));
            return;
        }
        $map['userId']=session('oto_userId');
        $map['userName']=I('userName');
        $map['userPhone']=I('userPhone');
        $map['areaId1']=I('areaId1');
        $map['areaId2']=I('areaId2');
        $map['areaId3']=I('areaId3');
        $map['address']=I('address');
        $map['createTime']=date('Y-m-d H:i:s',time());
        $r=M('user_address')->add($map);
        if($r){
            $this->ajaxReturn(array('status'=>0));
        }else{
            $this->ajaxReturn(array('status'=>-1));
        }
    }

    public function editAddr(){
        parent::isLogin();
        $id=I('id');
        $m= M('areas');
        $addr=M('user_address')->where(array('addressId'=>$id))->find();

        if($addr['areaId1']) $this->pr= $m->where(['areaId'=>$addr['areaId1']])->find();
        if($addr['areaId2']) $this->ci= $m->where(['areaId'=>$addr['areaId2']])->find();
        if($addr['areaId3']) $this->ar= $m->where(['areaId'=>$addr['areaId3']])->find();
        $this->addr=$addr;
        $this->area=$this->getArea();
        // dump(I('ref'));die;
        if(I('ref')){
            //点击返回按钮url
            $this->ref = '/Wx/Address/myAddr?ref='.I('ref');
        }else{
            $this->ref = '/Wx/Address/myAddr';
        }
        $this->ret = $_SERVER['REQUEST_URI'];
        $this->display('edit_address');
    }

    //保存编辑地址
    public  function editAddrHandle(){
        if(!session('oto_userId')){
            $this->ajaxReturn(array('status'=>-3));
            return;
        }
        $map['userId']=session('oto_userId');
        $map['addressId']=I('addrid');
        $map['userName']=I('userName');
        $map['userPhone']=I('userPhone');
        $map['lng']=I('lng');
        $map['lat']=I('lat');
        $map['number']=I('number');
        $map['address']=I('address');
        $r=M('user_address')->save($map);

        if($r){
            $this->ajaxReturn(array('status'=>0));
        }else{
            $this->ajaxReturn(array('status'=>-1));
        }
    }

    public function map()
    {
        parent::isLogin();
        $this->display();
    }

    public function mapList()
    {
        parent::isLogin();
        $this->display();
    }
}
